package com.tbit.uqbike.task;

import com.tbit.uqbike.TerGatewayMain;
import com.tbit.uqbike.service.redis.RedisService;
import com.tbit.uqbike.tergateway.config.TerGatewayConfig;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.tergateway.entity.TerTempData;
import com.tbit.uqbike.util.CollExUtils;
import com.tbit.uqbike.util.DateUtil;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by MyWin on 2018/3/13 0013.
 * 离线终端检测
 */
public class OfflineTerCheck implements Runnable {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OfflineTerCheck.class);

    @Override
    public void run() {
        try {
            List<TerTempData> mnos = TerGatewayData.getAllTerTempData();
            // 先检索需要释放的对象
            List<String> writeMnos = new LinkedList<>();
            List<String> delMnos = new LinkedList<>();
            int iWriteCnt = 0, iDelCnt = 0;
            Date now = new Date();
            for (TerTempData data : mnos) {
                // 先检查是否有缓存数据
                if (!data.haveCacheData()) {
                    // 时间是否超时了
                    Date dt = data.getLastPkgDt();
                    if (dt == null || DateUtil.GetTimeSpanHours(dt, now) > TerGatewayConfig.iDelMemTerObjTimeOutHour) {
                        delMnos.add(data.getSn());
                        iDelCnt++;
                        continue;
                    }
                }
                writeMnos.add(data.getSn());
                iWriteCnt++;
            }
            TerGatewayData.removeTerMnos(delMnos);
            List<List<String>> batHandleList = CollExUtils.spiltList(writeMnos, TerGatewayConfig.iRedisBatSize);
            // 插入数据
            if (!batHandleList.isEmpty()) {
                Date start = new Date();
                RedisService redis = TerGatewayMain.getRedis();
                // 先del数据
                String key = String.format("%s.tidset", TerGatewayConfig.gatewayNameIdent);
                redis.Key_Del(key);
                for (List<String> list : batHandleList) {
                    redis.Set_BatSetKey(key, list);
                }
                Date end = new Date();
                long lMs = end.getTime() - start.getTime();
                logger.info(String.format("Bat Record [%d] TerID,Free [%d] Ter Obj,Use [%d]ms", iWriteCnt, iDelCnt, lMs));
            }
        } catch (Exception e) {
            logger.error("OfflineTerCheck", e);
        }
    }
}
